const express=require("express")
const router=express.Router()

const mysql = require("mysql")
const conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: "yunheshop",
    port: '3306'
})

//加载购物车数据
router.get("/cart",(req,res)=>{
    let {user}=req.query;
    console.log(user);
    let sql="select * from cart,midata where cart.userId=? and midata.Id=cart.proId order by cart.cartId asc";
    conn.query(sql,[user],(err,result)=>{
        if(err){
            console.log("服务器出错");
            return ;
        }
        let data;
        if(result.length){
            data={
                code:0,
                list:result
            }
        }else{
            data={
                code:1,
                msg:"没有数据了"
            }
        }
        res.send(data);
    })
})

//删除购物车数据
router.delete("/cart",(req,res)=>{
    let {cartId}=req.query;
    let sql="delete from cart where cartId=?";
    conn.query(sql,[cartId],(err,result)=>{
        if(err){
            console.log("服务器出错");
            return ;
        }
        let data;
        if(result.affectedRows){
            data={
                code:0,
                msg:"删除成功"
            }
        }else{
            data={
                code:1,
                msg:"删除失败"
            }
        }
        res.send(data);
    })
})

//修改商品数量
router.put("/cart",(req,res)=>{
    let {cartId,num}=req.body;
    console.log(cartId,num);
    let sql="update cart set num=? where cartId=?";
    conn.query(sql,[num,cartId],(err,result)=>{
        console.log(result)
        if(err){
            console.log("服务器出错");
            return;
        }
        let data;
        if(result.affectedRows){
            data={
                code:0,
                msg:"修改成功"
            }
        }else{
            data={
                code:1,
                msg:"修改失败"
            }
        }
        res.send(data);
    })
})


module.exports=router;